package com.ly.juc.problem;



import org.junit.jupiter.api.Test;

import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Classname Problem1
 * @Description
 *
 * 1.交替打印
 * 3个线程  交替打印  A->B->C->A,循环10次
 *
 * 2.执行顺序
 * t1在t2前，t2在t3前
 *
 * @Date 2020/11/18 14:37
 * @Author 冷心影翼
 */
public class Problem1 {

	int flag = 0;

	ReentrantLock r = new ReentrantLock();
	Condition conditionA = r.newCondition();
	Condition conditionB = r.newCondition();
	Condition conditionC = r.newCondition();


	Thread A;
	Thread B;
	Thread C;

	@Test
	public void solution2() {

		A = new Thread(()->{
			System.out.println("A");
		});
		B = new Thread(()->{
			try {
				A.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("B");
		});
		C = new Thread(()->{
			try {
				B.join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("C");
		});
		A.start();
		B.start();
		C.start();
	}



	@Test
	public void solution() {
		new Thread(()->{
			for(int i=0;i<10;i++) {
				r.lock();
				try {
					while (flag == 0) {
						System.out.println("A");
						flag = 1;
						conditionB.signalAll();
					}
					conditionA.await();

				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				r.unlock();
			}
		}).start();
		new Thread(()->{
			for(int i=0;i<10;i++) {
				r.lock();
				try {
					while (flag == 1) {
						System.out.println("B");
						flag = 2;
						conditionC.signalAll();

					}
					conditionB.await();

				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				r.unlock();
			}
		}).start();
		new Thread(()->{
			for(int i=0;i<10;i++) {
				r.lock();
				try {
					while (flag == 2) {
						System.out.println("C");
						flag = 0;
						conditionA.signalAll();
					}
					conditionC.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				r.unlock();
			}
		}).start();

	}

}
